package com.ycrlkj.android.modulescore.main.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.SPStaticUtils;
import com.lxj.xpopup.impl.LoadingPopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.ycrlkj.android.modulescore.main.R;
import com.ycrlkj.android.modulescore.main.apiservice.UserApiService;
import com.ycrlkj.android.modulescore.main.databinding.FragmentUserInfoBinding;
import com.ycrlkj.android.modulescore.main.entity.User;
import com.ycrlkj.android.modulescore.main.viewmodel.UserViewModel;
import com.ycrlkj.android.modulespublic.common.constant.RoutePath;
import com.ycrlkj.android.modulespublic.common.net.exception.ApiException;
import com.ycrlkj.android.modulespublic.common.net.exception.ApiExceptionHandler;
import com.ycrlkj.android.modulespublic.common.net.exception.ErrorConsumer;
import com.ycrlkj.android.modulespublic.common.net.transformer.ResponseTransformer;
import com.ycrlkj.android.modulespublic.common.utils.xpopup.XPopupUtil;
import com.ycrlkj.android.modulespublic.common.widget.titlebar.MTitleBar;
import javax.inject.Inject;
import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class UserInfoFragment extends Fragment {

    private FragmentUserInfoBinding binding;

    private UserCenterActivity activity;

    private UserViewModel viewModel;

    @Inject
    UserApiService userApiService;


    public UserInfoFragment() {
    }

    public static UserInfoFragment newInstance() {
        UserInfoFragment fragment = new UserInfoFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        activity = (UserCenterActivity) getActivity();
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_user_info, container, false);

        viewModel = new ViewModelProvider(activity).get(UserViewModel.class);
        binding.setViewModel(viewModel);

        initTitleBar();

        getUserBySp();

        return binding.getRoot();
    }

    public void initTitleBar() {
        MTitleBar titleBar = binding.mTitleBar;
        titleBar.setBtnEvents(new MTitleBar.BtnEvents() {
            @Override
            public void setBtnLeftOnClickListener() {
                activity.finish();
            }

            @Override
            public void setBtnRightOnClickListener() {
                //隐藏按钮, 无事件
            }
        });
    }

    //onStart() 方法, 每次显示此fragment时执行
    //在activity内的几个页面内每次切换都要请求 user 信息有加载动画, 用户体验不好, 不再做每次显示时请求用户信息
//    @Override
//    public void onStart(){
//        super.onStart();
//        Logger.e("每次显示UserInfoFragment时调用");
//        getUser();
//    }

    public void getUserBySp(){
        String userStr = SPStaticUtils.getString("user");

        if (TextUtils.isEmpty(userStr)) {
            XPopupUtil.showModal(activity, "请登录", new OnConfirmListener() {
                @Override
                public void onConfirm() {
                    ARouter.getInstance().build(RoutePath.PAGE_LOGIN).navigation();
                }
            });
        }

        User user = JSON.parseObject(userStr, User.class);
        viewModel.getUser().setValue(user);
        binding.setViewModel(viewModel);
    }

    @SuppressLint("CheckResult")
    public void getUser() {

        String userId = SPStaticUtils.getString("userId");

        if (TextUtils.isEmpty(userId)) {
            XPopupUtil.showModal(activity, "请登录", new OnConfirmListener() {
                @Override
                public void onConfirm() {
                    ARouter.getInstance().build(RoutePath.PAGE_LOGIN).navigation();
                }
            });
        }

        LoadingPopupView loadingPopupView = XPopupUtil.showLoading(activity);
        XPopupUtil.hideLoadingDelay(loadingPopupView);
        userApiService.getById(userId)
                .compose(ResponseTransformer.obtain())
                .subscribe(user -> {
                    XPopupUtil.hideLoading(loadingPopupView);
                    viewModel.getUser().setValue(user);
                    binding.setViewModel(viewModel);

                    activity.writeUserToSP(user);
                }, new ErrorConsumer() {
                    @Override
                    protected void error(ApiException e) {
                        XPopupUtil.hideLoading(loadingPopupView);
                        ApiExceptionHandler.doWith(activity, e);
                    }
                });

    }

}